<template>
  <view class="page-container">
    <!-- 顶部搜索区 -->
    <view class="search-section">
      <uni-search-bar
        radius="100"
        placeholder="搜索医生/科室"
        v-model="searchText"
        @confirm="handleSearch"
        bgColor="#F5F8FF"
        :cancelButton="false"
        :focus="false"
      />
    </view>

    <!-- 轮播图区域 -->
    <view class="swiper-section">
      <swiper
        class="swiper"
        circular
        :indicator-dots="true"
        :autoplay="true"
        :interval="3000"
        :duration="500"
        indicator-color="rgba(255, 255, 255, 0.6)"
        indicator-active-color="#FFFFFF"
      >
        <swiper-item v-for="(item, index) in bannerList" :key="index">
          <image 
          :src="item.imageUrl" 
          mode="aspectFill" 
          class="swiper-image"
          lazy-load
          />
        </swiper-item>
      </swiper>
    </view>

    <!-- 功能导航区 -->
    <view class="nav-section">
      <view 
      class="nav-item" 
      v-for="(item, index) in navList" 
      :key="index"
      @click="handleNavClick(item)"
      >
        <image :src="item.icon" mode="aspectFit" class="nav-icon" />
        <text class="nav-text">{{ item.title }}</text>
      </view>
    </view>

    <!-- 推荐医生区 -->
    <view class="doctor-section">
      <view class="section-header">
        <text class="section-title">推荐医生</text>
        <view class="more-link" @click="navigateTo('/pages/index/doctor-list')">
          <text class="more-text">更多</text>
          <uni-icons type="right" size="14" color="#666666" />
        </view>
      </view>
      <scroll-view 
      class="doctor-list" 
      scroll-y
      :show-scrollbar="false"
        enhanced
        :bounces="true"
      >
        <DoctorCard
          v-for="(doctor, index) in doctorList"
          :key="index"
          :doctor="doctor"
          @consult="handleConsult"
        />
      </scroll-view>
    </view>

    <!-- 健康资讯区 -->
    <view class="news-section">
      <view class="section-header">
        <text class="section-title">健康资讯</text>
        <view class="more-link" @click="navigateTo('/pages/index/news-list')">
          <text class="more-text">更多</text>
          <uni-icons type="right" size="14" color="#666666" />
        </view>
      </view>
      <view class="news-list">
        <NewsCard
          v-for="(news, index) in newsList"
          :key="index"
          :news="news"
          @click="handleNewsClick"
        />
      </view>
    </view>

    <!-- 客服按钮 -->
    <button 
      class="service-btn" 
      open-type="contact" 
      hover-class="service-btn-hover"
      :style="serviceButtonStyle"
      @touchmove.stop.prevent="handleTouchMove"
    >
      <uni-icons type="headphones" size="24" color="#FFFFFF" />
    </button>
  </view>
</template>

<script>
import { ref, onMounted } from 'vue';
import DoctorCard from './components/DoctorCard.vue';
import NewsCard from './components/NewsCard.vue';
import { apiBaseUrl, minioBaseUrl } from '../../config/api';

export default {
  components: {
    DoctorCard,
    NewsCard
  },
  setup() {
    const searchText = ref('');
    const doctorList = ref([]);
    const newsList = ref([]);

    // 获取医生列表
    const getDoctorList = async (keyword = '') => {
      try {
        uni.showLoading({
          title: '加载中...'
        });
        
        const [err, res] = await uni.request({
          url: `${apiBaseUrl}/doctors/selectTelByNameOrDeptName`,
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: `keyword=${encodeURIComponent(keyword)}`
        }).then(res => [null, res]).catch(err => [err, null]);

        if (err) {
          throw new Error('网络请求失败');
        }

        const { code, doctors } = res.data;
        if (code === 200) {
          // 将对象转换为数组
          doctorList.value = Object.values(doctors);
        } else {
          uni.showToast({
            title: '获取医生列表失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    };

    // 获取健康资讯列表
    const getHealthGuides = async () => {
      try {
        uni.showLoading({
          title: '加载中...'
        });
        
        const [err, res] = await uni.request({
          url: `${apiBaseUrl}/health/guides/selectByViews`,
          method: 'GET'
        }).then(res => [null, res]).catch(err => [err, null]);

        if (err) {
          throw new Error('网络请求失败');
        }

        const { code, healthGuides } = res.data;
        if (code === 200) {
          newsList.value = healthGuides;
        } else {
          uni.showToast({
            title: '获取健康资讯失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    };

    // 搜索处理
    const handleSearch = () => {
      getDoctorList(searchText.value.trim());
    };

    // 页面加载时获取默认医生列表和健康资讯
    onMounted(() => {
      getDoctorList();
      getHealthGuides();
    });

    const bannerList = ref([
      {
        imageUrl: 'https://ai-public.mastergo.com/ai/img_res/86a4fe0c527a43e49d4d332d1353339a.jpg',
      },
      {
        imageUrl: 'https://ai-public.mastergo.com/ai/img_res/eaa88527950e84e5d40d21f4679d5807.jpg',
      },
      {
       imageUrl: 'https://ai-public.mastergo.com/ai/img_res/26bb073946d3ee2a80bf2b33c1805949.jpg'
      },
      {
        imageUrl: 'https://ai-public.mastergo.com/ai/img_res/474177ae668bd4fa3a5c5b7d88a596cc.jpg',
      },
    ]);

    const navList = ref([
      {
        title: '预约挂号',
        icon: 'https://ai-public.mastergo.com/ai/img_res/0c438c48f5a324b84a5baa0115d77243.jpg',
        path: '/pages/index/Make-appointment/Registration-instructions'
      },
      {
        title: '快速问诊',
        icon: 'https://ai-public.mastergo.com/ai/img_res/4d62128bb27d94435063b1485c5f56fb.jpg',
        path: '/pages/index/quick-consultation/quick-consultation'
      },
      {
        title: '健康档案',
        icon: 'https://ai-public.mastergo.com/ai/img_res/7aea53f7297b426729edfee7fe50d591.jpg',
        path: '/pages/index/health-record/health-record'
      },
      {
        title: '体检预约',
        icon: 'https://ai-public.mastergo.com/ai/img_res/4a5d56da50ac3e77ad4c67c092455afe.jpg',
        path: '/pages/index/physical-examination/physical-examination'
      },
    ]);

    const handleNavClick = (item) => {
      if (item.path) {
        uni.navigateTo({
          url: item.path,
          fail: (err) => {
            console.error('导航失败：', err);
            uni.showToast({
              title: '页面跳转失败',
              icon: 'none'
            });
          }
        });
      }
    };

    // 页面跳转方法
    const navigateTo = (url) => {
      uni.navigateTo({
        url
      });
    };

    // 处理咨询
    const handleConsult = (doctor) => {
      // 将医生信息转换为查询字符串
      const query = encodeURIComponent(JSON.stringify({
        id: doctor.id,
        name: doctor.name,
        department: doctor.department,
        title: doctor.title,
        avatar: doctor.avatar,
        specialty: doctor.specialty
      }));
      
      // 跳转到咨询页面
      uni.navigateTo({
        url: `/pages/consultation/chat?doctor=${query}`
      });
    };

    // 健康资讯点击事件
    const handleNewsClick = (news) => {
      uni.navigateTo({
        url: `/pages/index/health-guides/health-guides?id=${news.id}`
      })
    }

    // 客服按钮位置
    const serviceButtonStyle = ref({
      bottom: '120rpx'
    });

    // 处理拖动
    const handleTouchMove = (e) => {
      const touch = e.touches[0];
      const pageHeight = uni.getSystemInfoSync().windowHeight;
      let newBottom = pageHeight - touch.clientY;
      
      // 限制上下移动范围
      if (newBottom < 100) newBottom = 100;
      if (newBottom > pageHeight - 100) newBottom = pageHeight - 100;
      
      serviceButtonStyle.value.bottom = `${newBottom}rpx`;
    };

    return {
      searchText,
      doctorList,
      newsList,
      bannerList,
      navList,
      serviceButtonStyle,
      handleSearch,
      handleNavClick,
      navigateTo,
      handleConsult,
      handleNewsClick,
      handleTouchMove,
      getDoctorList,
      getHealthGuides
    }
  },
  // 下拉刷新回调
  onPullDownRefresh() {
    Promise.all([
      this.getDoctorList(),
      this.getHealthGuides()
    ]).then(() => {
      uni.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 1000
      });
    }).catch(() => {
      uni.showToast({
        title: '刷新失败',
        icon: 'none'
      });
    }).finally(() => {
      // 停止下拉刷新动画
      uni.stopPullDownRefresh();
    });
  }
}
</script>

<style>
page {
  height: 100%;
  background-color: #F5F8FF;
}

.page-container {
  padding-top: 73px; /* 增加padding-top，使内容位于胶囊按钮下方 */
  min-height: 100vh;
  background-color: #f5f5f5;
  box-sizing: border-box;
}

.search-section {
  padding: 20rpx 30rpx;
  background-color: #FFFFFF;
  position: relative;
  z-index: 99;
  /* margin-top: 120rpx; */
}

/* 修改搜索框样式 */
:deep(.uni-searchbar) {
  padding: 0;
}

:deep(.uni-searchbar__box) {
  border-radius: 100rpx;
  background-color: #F5F8FF;
}

.swiper-section {
  margin: 20rpx 30rpx;
  border-radius: 16rpx;
  overflow: hidden;
}

.swiper {
  height: 300rpx;
}

.swiper-image {
  width: 100%;
  height: 100%;
}

.nav-section {
  display: flex;
  justify-content: space-around;
  padding: 30rpx;
  background-color: #FFFFFF;
  margin: 20rpx 30rpx;
  border-radius: 16rpx;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.nav-icon {
  width: 80rpx;
  height: 80rpx;
  margin-bottom: 10rpx;
}

.nav-text {
  font-size: 14px;
  color: #333333;
}

.doctor-section {
  background-color: #FFFFFF;
  margin: 20rpx 30rpx;
  border-radius: 16rpx;
  padding: 30rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
}

.more-link {
  display: flex;
  align-items: center;
}

.more-text {
  font-size: 14px;
  color: #666666;
  margin-right: 4rpx;
}

.doctor-list {
  height: 600rpx;
  overflow: auto;
}

.news-section {
  background-color: #FFFFFF;
  margin: 20rpx 30rpx;
  border-radius: 16rpx;
  padding: 30rpx;
}

.news-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1px solid #EEEEEE;
}

.news-image {
  width: 200rpx;
  height: 150rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.news-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.news-title {
  font-size: 16px;
  color: #333333;
  margin-bottom: 10rpx;
  font-weight: bold;
}

.news-desc {
  font-size: 14px;
  color: #666666;
  margin-bottom: 20rpx;
}

.news-meta {
  display: flex;
  justify-content: space-between;
}

.news-time, .news-views {
  font-size: 12px;
  color: #999999;
}

.service-btn {
  position: fixed;
  right: 30rpx;
  width: 100rpx;
  height: 100rpx;
  background-color: #4A90E2;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(74, 144, 226, 0.3);
  padding: 0;
  margin: 0;
  border: none;
  line-height: 1;
  z-index: 999;
  transition: bottom 0.1s ease-out;
}

.service-btn-hover {
  background-color: #3A80D2;
  transform: scale(0.95);
}

/* 重置button的默认样式 */
.service-btn::after {
  border: none;
}
</style>
